<?php
 

class Weimod {

    //private $this->appId_weimob = "adf9c7acd9845d0ef577aec3ad94b25d";
    //private $this->appSecret_weimob = 'a8e32829cb998926d76b6ecf5033a98e';
    
    const WEIMOB_CODE_URL = 'https://open.weimob.com/oauth2/openid/authorize?enter=wm&client_id=%s&redirect_uri=%s&response_type=code&scope=%s&state=STATE';
    const WEIMOB_TOKEN_URL = 'https://open.weimob.com/oauth2/openid/access_token';
    const WEIMOB_USERINFO_URL = 'https://open.weimob.com/oauth2/openid/userinfo?access_token=%s';

    private $appId_weimob;
    private $appSecret_weimob;
    private $token = "o5Dttg7seGr7n8G8bu3r";
    private $encodingAesKey;
    private $encrypt_type;
    private $appid;
    private $appsecret;
    private $access_token;
    private $jsapi_ticket;
    private $api_ticket;
    private $user_token;
    private $partnerid;
    private $partnerkey;
    private $paysignkey;
    private $postxml;
    private $_msg;
    private $_funcflag = false;
    private $_receive;
    private $_text_filter = true;
    public $debug = false;
    public $errCode = 40001;
    public $errMsg = "no access55";
    public $logcallback;

    
    
     public function __construct($appId, $appSecret) {
        $this->appId_weimob = $appId;
        $this->appSecret_weimob = $appSecret;
    }

    /**
     * For weixin server validation
     */
    private function checkSignature($str = '') {
        $signature = isset($_GET["signature"]) ? $_GET["signature"] : '';
        $signature = isset($_GET["msg_signature"]) ? $_GET["msg_signature"] : $signature; //如果存在加密验证则用加密验证段
        $timestamp = isset($_GET["timestamp"]) ? $_GET["timestamp"] : '';
        $nonce = isset($_GET["nonce"]) ? $_GET["nonce"] : '';

        $token = $this->token;

        $tmpArr = array($token, $timestamp, $nonce, $str);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * For weixin server validation
     * @param bool $return 是否返回
     */
    public function valid($return = false) {
        $encryptStr = "";
        if ($_SERVER['REQUEST_METHOD'] == "POST") {
            $postStr = file_get_contents("php://input");
            $array = (array) simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $this->encrypt_type = isset($_GET["encrypt_type"]) ? $_GET["encrypt_type"] : '';

            if ($this->encrypt_type == 'aes') { //aes加密 
                $encryptStr = $array['Encrypt'];
                $pc = new Prpcrypt($this->encodingAesKey);
                $array = $pc->decrypt($encryptStr, $this->appid);
                if (!isset($array[0]) || ($array[0] != 0)) {
                    if (!$return) {
                        die('decrypt error!');
                    } else {
                        return false;
                    }
                }
                $this->postxml = $array[1];
                if (!$this->appid)
                    $this->appid = $array[2]; //为了没有appid的订阅号。
            } else {
                $this->postxml = $postStr;
            }
        } elseif (isset($_GET["echostr"])) {
            $echoStr = $_GET["echostr"];
            if ($return) {
                if ($this->checkSignature()) {
                    return $echoStr;
                } else
                    return false;
            } else {
                if ($this->checkSignature()) {
                    die($echoStr);
                } else {
                    die('no access111111');
                }
            }
        }

        if (!$this->checkSignature($encryptStr)) {
            if ($return)
                return false;
            else {
                die('no access2');
            }
        }
        return true;
    }

    /**
     * oauth 授权跳转接口
     * @param string $callback 回调URI
     * @param string $scope snsapi_base, snsapi_userinfo
     * @return string
     */
    public  function GetWeimobCode($page_url, $scope='snsapi_base') { 
        $page_url = urlencode($page_url); 
        $code_url = sprintf(self::WEIMOB_CODE_URL, $this->appId_weimob, $page_url,$scope);
        return $code_url;
    }

    /**
     * 通过code获取Access Token
     * @return array {access_token,expires_in,refresh_token,openid,scope}
     */
    public function getOauthAccessToken() {
        $code = isset($_GET['code']) ? $_GET['code'] : '';
        if (!$code)
            return false;

        $param = "grant_type=authorization_code&client_id=%s&client_secret=%s&code=%s";
        $param = sprintf($param, $this->appId_weimob, $this->appSecret_weimob, $code);
        
        $result = $this->http_post(self::WEIMOB_TOKEN_URL, $param);
        
        if (!empty($result)) {
            $json = json_decode($result, true); 
            return $json;
        }
        return false;
    }

    /**
     * 刷新access token并续期
     * @param string $refresh_token
     * @return boolean|mixed
     */
    public function getOauthRefreshToken($refresh_token) {
        
        $param = "grant_type=refresh_token&client_id=%s&client_secret=%s&refresh_token=%s";
        $param = sprintf($param, $this->appId_weimob, $this->appSecret_weimob, $refresh_token);
        // echo $param; exit;

        $result = $this->http_post(self::WEIMOB_TOKEN_URL, $param);

        if (!empty($result)) {
            $json = json_decode($result, true);
            return $json;
        }
        return false;
    }

    
    /**
     * 通过Access Token获取UserInfo
     * @return array {access_token,expires_in,refresh_token,openid,scope}
     */
    public function getUSERINFO($accesstoken) { 
        if (!$accesstoken)
            return false;
        $url = sprintf(self::WEIMOB_USERINFO_URL, $accesstoken); 
        $result = $this->http_get($url,''); 
        if (!empty($result)) {
            $json = json_decode($result, true); 
            return $json;
        }
        return false;
    }
    
    /**
     * GET 请求
     * @param string $url
     */
    private function http_get($url) {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
         
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
         
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    /**
     * POST 请求
     * @param string $url
     * @param array $param
     * @param boolean $post_file 是否文件上传
     * @return string content
     */
    private function http_post($url, $param, $post_file = false) {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            if (is_array($param)){
                $aPOST = array();
                foreach ($param as $key => $val) {
                    $aPOST[] = $key . "=" . urlencode($val);
                }
                $strPOST = join("&", $aPOST);
            }
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        $this->log("url:" . $url);
        $this->log("content:" . $sContent);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }


    private function log($message) {
        $serverFilePath = realpath(dirname(__FILE__)); //$_SERVER["SCRIPT_FILENAME"];

        $doc_dir = strrpos($serverFilePath, '/plugin');
        $doc_dir = substr($serverFilePath, 0, $doc_dir + 1);   //project root

        $lfile = $doc_dir . '/logs';
        if (!is_dir($lfile)) {
            $dirs = explode('/', $lfile);
            $dir2 = '';
            foreach ($dirs as $part) {
                $dir2.=$part . '/';
                if (!is_dir($dir2) && strlen($dir2) > 0) {
                    mkdir($dir2, 0777);
                }
            }
        }
       // exec('chmod -R 777 /var/www/wxshop.shjieta.com.cn/logs');

        $lfile=$lfile.'/weimod';
        $today = date('Y-m-d');
        $fp = fopen($lfile . '_' . $today . '.log', 'a') or exit("Can't open $lfile!");

        $time = date('H:i:s');
        fwrite($fp, "$time  $message\n");
    }



}

?>